-- https://github.com/hchunhui/librime-lua/wiki/Objects
local logger = { _version = "0.1.0" }

logger.usecolor = true
-- logger.outfile = nil
logger.outfile = "D:/temp/rime-log.txt"
logger.level = "trace"


local modes = {
  { name = "trace", color = "\27[34m", },
  { name = "debug", color = "\27[36m", },
  { name = "info",  color = "\27[32m", },
  { name = "warn",  color = "\27[33m", },
  { name = "error", color = "\27[31m", },
  { name = "fatal", color = "\27[35m", },
}


local levels = {}
for i, v in ipairs(modes) do
  levels[v.name] = i
end


local round = function(x, increment)
  increment = increment or 1
  x = x / increment
  return (x > 0 and math.floor(x + .5) or math.ceil(x - .5)) * increment
end


local _tostring = tostring

local tostring = function(...)
  local t = {}
  for i = 1, select('#', ...) do
    local x = select(i, ...)
    if type(x) == "number" then
      x = round(x, .01)
    end
    t[#t + 1] = _tostring(x)
  end
  return table.concat(t, " ")
end


for i, x in ipairs(modes) do
  local nameupper = x.name:upper()
  logger[x.name] = function(...)
    -- Return early if we're below the log level
    if i < levels[logger.level] then
      return
    end

    local msg = tostring(...)
    local info = debug.getinfo(2, "Sl")
    local lineinfo = info.short_src .. ":" .. info.currentline

    -- Output to console
    -- print(string.format("%s[%-6s%s]%s %s: %s",
    --   logger.usecolor and x.color or "",
    --   nameupper,
    --   os.date("%H:%M:%S"),
    --   logger.usecolor and "\27[0m" or "",
    --   lineinfo,
    --   msg))

    -- Output to log file
    if logger.outfile then
      local file = io.open(logger.outfile, "a")
      local str = string.format("[%-6s%s] %s: %s\n",
        nameupper, os.date("%Y-%m-%d %H:%M:%S"), lineinfo, msg)
      if file then
        file:write(str)
        file:close()
      end
    end
  end
end

return logger
